// pages/category/category.js
const {
  get
} = require('../../utils/request')
const {
  baseUrl
} = require('../../utils/config')
Page({
  data: {
    // 分类名称数据
    categoryNameData: [],
    // 文章列表数据
    articleListData: [],
    baseUrl: baseUrl,
    isAllActive: true,
  },
  onLoad(options) {
    this.getCategoryNameData()
    this.getArticleListDataByCate()
  },
  // 获取分类名称数据
  async getCategoryNameData() {
    let result = await get(`${baseUrl}categoryName`)
    const newData = result.map(item => ({
      ...item,
      isActive: false,
    }));
    this.setData({
      categoryNameData: newData
    })
  },
  // 选择分类
  selectCategory(e) {
    const category_id = e.currentTarget.dataset.categoryId;
    const isAll = category_id === 'undefined';
    this.setData({
      categoryNameData: this.data.categoryNameData.map(item => ({
        ...item,
        isActive: !isAll && (item.category_id === category_id)
      })),
      isAllActive: isAll
    });
    this.getArticleListDataByCate(isAll ? undefined : category_id)
  },
  // 通过分类获取文章列表数据
  async getArticleListDataByCate(category_id = undefined) {
    let result = await get(`${baseUrl}articleListByCate`,{category_id})
    this.setData({
      articleListData: result
    })
  },
  // 跳转详情页
  goDetail(e) {
    const article_id = e.currentTarget.dataset.articleId;
    wx.navigateTo({
      url: `/pages/detail/detail?article_id=${article_id}`,
    })
  }
})